﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Threading;
namespace TestPhone
{
    public class CustomTimelineCollection : List<CustomMarker>, IDisposable
    {
        public CustomTimelineCollection(MediaElement Source)
        {
            this.Source = Source;
            var MainTask = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        MainLoopCancelSource.Token.ThrowIfCancellationRequested();
                        Source.Dispatcher.BeginInvoke(DoPlayerPosition);
                        System.Threading.Thread.Sleep(10);
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
            }, MainLoopCancelSource.Token);
        }
        public MediaElement Source { get; private set; }
        CancellationTokenSource MainLoopCancelSource = new CancellationTokenSource();

        void DoPlayerPosition()
        {
            if (Source.CurrentState == System.Windows.Media.MediaElementState.Stopped)
            {
                MainLoopCancelSource.Cancel();
                return;
            }

            var pos = Source.Position;
            var items = this.Where(m => (pos - m.Time).TotalMilliseconds <= 20 && m.Time <= pos);
            if (LastItems!=null)
            {
                items = items.Except(LastItems).ToArray();
            }
            else
            {
                items = items.ToArray();
            }
            if (items != null && items.Count() > 0 )
            {
                foreach (var item in items)
                {
                    OnMarkerReached(item);
                }
            }
            LastItems = items;
        }
        IEnumerable<CustomMarker> LastItems = null;
        void OnMarkerReached(CustomMarker m)
        {
            if (Source != null)
            {
                if (MarkerReached != null)
                {
                    MarkerReached(this, new MarkerReachedEventArgs(m));
                }
            }
        }

        public event EventHandler<MarkerReachedEventArgs> MarkerReached;

        public void Dispose()
        {
            //throw new NotImplementedException();
            MainLoopCancelSource.Cancel();
        }
    }
    public class MarkerReachedEventArgs : EventArgs
    {
        internal MarkerReachedEventArgs(CustomMarker m)
        {
            Marker = m;
        }
        public CustomMarker Marker { get; private set; }
    }

    public class CustomMarker
    {
        public TimeSpan Time { get; set; }
    }
}
